#include <QTreeView>
#include <QShortcut>
#include <QTimer>
#include <QDesktopWidget>

#include "include/PersistentDialog.h"
#include "ui_PersistentDialog.h"
#include "include/treemodel.h"
#include "include/CardInfo.h"
#include "include/RichText.h"

#include <assert.h>
#include <iostream>

namespace
{
	QString stringifyLineage(const QList<QString>& list)
	{
		QString str = "";
		for (QList<QString>::const_iterator it = list.begin(); it != list.end(); it++)
		{
			str += *it;
			if (it + 1 != list.end())
				str += " > ";
		}
		return str;
	}
}

PersistentDialog::PersistentDialog(QWidget *parent) :
	QDialog(parent),
	ui(new Ui::PersistentDialog)
{
	ui->setupUi(this);

	setDocumentFont(font());

	m_shortcuts["show"] =					new QShortcut(QKeySequence(tr("s")), this);
	connect(m_shortcuts["show"],			SIGNAL(activated()), this, SLOT(showAnswer()));

	m_shortcuts["knowIt"] =				new QShortcut(QKeySequence(tr("k")), this);
	connect(m_shortcuts["knowIt"],		SIGNAL(activated()), this, SLOT(knewIt()));

	m_shortcuts["fail"] =					new QShortcut(QKeySequence(tr("f")), this);
	connect(m_shortcuts["fail"],			SIGNAL(activated()), this, SLOT(closeWithFail()));

	QShortcut* restartTimerShortcut = new QShortcut(QKeySequence("R"), this);
	m_shortcuts["restartTimer"] = restartTimerShortcut;
	restartTimerShortcut->setWhatsThis("Restart Answer Timer");
	connect(restartTimerShortcut, SIGNAL(activated()), this, SLOT(startAnsweringTimer()));

	connect(ui->w_knewIt, SIGNAL(clicked()), this, SLOT(knewIt()));
	connect(ui->w_fail, SIGNAL(clicked()), this, SLOT(closeWithFail()));
	connect(ui->w_showAnswer, SIGNAL(clicked()), this, SLOT(showAnswer()));
}

PersistentDialog::~PersistentDialog()
{
	delete ui;
}

void PersistentDialog::show()
{
	TreeItem* ti = m_cardInfo.m_treeItem;

	setDialogHeight(ti != 0 && ti->hasImage(TreeItem::QuestionColumn) ? 500 : 300);

	QDialog::show();
}

const CardInfo& PersistentDialog::cardInfo() const
{
	return m_cardInfo;
}

void PersistentDialog::setCardInfo(CardInfo value)
{
	m_cardInfo = value;

	if (m_cardInfo.m_card != 0)
	{
		displayCard(m_cardInfo);
		m_cardInfo.m_card->setDisplayed();

		ui->w_answerArea->hide();
	}
}

void PersistentDialog::knewIt()
{
	if (m_cardInfo.m_card == 0)
		return;

	m_cardInfo.m_card->setKnewIt();
	registerTimeToAnswer();

	accept();
}

void PersistentDialog::showAnswer()
{
	if (m_cardInfo.m_card == 0)
		return;

	TreeItem* ti = m_cardInfo.m_treeItem;

	setDialogHeight(ti != 0 && ti->hasImage(TreeItem::AnswerColumn) ? 500 : 300);

	ui->w_questionArea->hide();
	ui->w_answerArea->show();
	ui->w_showAnswer->hide();

	emit answerDisplayed();
}


void PersistentDialog::closeWithFail()
{
	if (m_cardInfo.m_card == 0)
		return;

	registerTimeToAnswer();

	accept();
}

void PersistentDialog::reject()
{
	if (m_cardInfo.m_card != 0)
	{
		m_cardInfo.m_card->setDisplayed(false);
	}

	QDialog::reject();
}

void PersistentDialog::setDialogHeight(int height)
{
	QDesktopWidget *desktop = QApplication::desktop();

	int screenWidth = desktop->width();
	int screenHeight = desktop->height();

	int xpos = (screenWidth - 589) / 2;
	int ypos = (screenHeight - height) / 2;

	this->setGeometry(xpos, ypos, 589, height);
}


void PersistentDialog::displayCard(const CardInfo& info)
{
	assert(info.m_card);
	ui->w_questionArea->clear();
	ui->w_answerArea->clear();

	TreeItem* ti = info.m_treeItem;

	QString lineage = stringifyLineage(info.m_lineage);

	ui->w_breadcrumbsArea->clear();
	ui->w_breadcrumbsArea->insertPlainText(lineage);

	QString question = RichText::formatToHTML(info.m_card->getQuestion());
	ui->w_questionArea->setHorizontalAlignment(Qt::AlignCenter);

	if (ti != 0 && ti->hasImage(TreeItem::QuestionColumn))
	{
		QImage image = ti->image(TreeItem::QuestionColumn);
		ui->w_questionArea->setImageResource(image);
		question = RichText::appendImage(question, ui->w_questionArea->imageResourceName());
	}

	QString questionHtml = "<html><body>" + question + "</body></html>";
	ui->w_questionArea->setHtml(questionHtml);

	QString answer = info.m_card->getAnswer();
	ui->w_answerArea->setHorizontalAlignment(Qt::AlignCenter);

	bool noData = answer.isEmpty() && (info.m_treeItem == 0 || !info.m_treeItem->hasImage(TreeItem::AnswerColumn));

	if (noData)
		answer = "&lt;no answer&gt;"; //&lt; is "<", &gt; is ">" - the symbols which are disallowed in html
	else
	{
		TreeItem* ti = info.m_treeItem;
		if (ti != 0 && ti->hasImage(TreeItem::AnswerColumn))
		{
			QImage image = ti->image(TreeItem::AnswerColumn);

			ui->w_answerArea->setImageResource(image);
			answer = RichText::appendImage(answer, ui->w_answerArea->imageResourceName());
		}
	}

	QString answerHtml = "<html><body><p>" + RichText::formatToHTML(answer) + "</p></body></html>";
	ui->w_answerArea->setHtml(answerHtml);
}


void PersistentDialog::showEvent(QShowEvent * evt)
{
	startAnsweringTimer();
	QDialog::showEvent(evt);
}


void PersistentDialog::startAnsweringTimer()
{
//	m_timeToAnswerStart = QDateTime::currentDateTimeUtc();
}


void PersistentDialog::registerTimeToAnswer()
{
	if (m_cardInfo.m_card == 0 || m_timeToAnswerStart.isNull())
		return;

//	m_cardInfo.m_card->registerTimeToAnswerMs(m_timeToAnswerStart.msecsTo(QDateTime::currentDateTimeUtc()));
}


QFont PersistentDialog::documentFont() const
{
	return m_documentFont;
}

void PersistentDialog::setDocumentFont(QFont font)
{
	m_documentFont = font;
	ui->w_questionArea->document()->setDefaultFont(font);
	ui->w_answerArea->document()->setDefaultFont(font);
}
